package com.yc.damai.web;

import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class RabbitMQActioni {

    ////////////////////////// 简单模式 /////////////////////////

    // 消费端
    @RabbitListener(queuesToDeclare = @Queue("simpleMsg"))
    public void recvSimpleMessage(String msg){
        System.out.println(msg);
    }

    @Resource
    RabbitTemplate rabbitTemplate;

    @RequestMapping("sendSimpleMessage")
    public String sendSimpleMessage(String msg){
        rabbitTemplate.convertAndSend("simpleMsg",msg);
        return "简单消息发送完成!";
    }

    ////////////////////////// 工作模式 /////////////////////////
    @RequestMapping("sendWorkMessage")
    public String sendWorkMessage(String msg){
        for (int i = 0; i < 10; i++) {
            rabbitTemplate.convertAndSend("workMsg", msg + " " + i);
        }
        return "工作模式消息发送完成!";
    }
    @RabbitListener(queuesToDeclare = @Queue("workMsg"))
    public void recvWorkMessage1(String msg){
        System.out.println("recvWorkMessage 1: "+msg);
    }

    @RabbitListener(queuesToDeclare = @Queue("workMsg"))
    public void recvWorkMessage2(String msg){
        System.out.println("recvWorkMessage 2: "+msg);
    }

    //////////////////////////// 广播消息 ////////////////////////////
    @RequestMapping("sendFanoutMessage")
    public String sendFanoutMessage(String msg){
        for (int i = 0; i < 10; i++) {
            rabbitTemplate.convertAndSend("fanoutMsg",
                    "", msg + " " + i);
        }
        return "广播消息发送完成";
    }

    @RabbitListener(bindings = {@QueueBinding(
            value=@Queue,
            exchange = @Exchange(value="fanoutMsg", type = ExchangeTypes.FANOUT))})
    public void recvFanoutMsg1(String msg){
        System.out.println("recvFanoutMsg1 : " + msg);
    }

    @RabbitListener(bindings = {@QueueBinding(
            value=@Queue,
            exchange = @Exchange(value="fanoutMsg", type = ExchangeTypes.FANOUT))})
    public void recvFanoutMsg2(String msg){
        System.out.println("recvFanoutMsg2 : " + msg);
    }

}
